<?php

/*
*	$version: 2009-5-19 14:52:25 stable 2.0
*	$id: Template.class.php
*	$author: taoFeng
*	$mailto: font99@Gmail.com
*	$license: This is not a freeware
*/

if (!defined('IN_LEKO')) {header("HTTP/1.0 403 Forbidden");exit;}

class Template {
	private $resDir					= 'res/';
	private $cacheHtmDir			= 'var/cache/htm/';
	private $htmCacheDir			= '';//缓存目录
	private $htmFileExt				= 'htm';//摸版后缀
	private $htmCacheExt			= 'php';//缓存文件后缀
	private $htmName				= 'index';//默认摸版名
	private $langHandle				= '_L';//语言包对象

	public function setViewName($_viewname) {
		global $_G;
		$this->htmName = $_viewname;
		if (!isset($_G['modName']))
			$_G['modName'] = 'index';
		$this->htmCacheDir .= $_G['modName'] . '_' . $this->htmName . DIRECTORY_SEPARATOR;
		if (!is_dir($this->htmCacheDir)) @mkdir ($this->htmCacheDir);
	}
	
	public function __construct($_rootdir = '' , $_cachedir = '') {
		global $_R,$_G;

		if (count($_REQUEST)){
			foreach($_REQUEST as $_k => $_v)
				$_R[$_k] = leko_htmlspecialchars($_v);
		}

		if (!empty($_rootdir)) $this->resDir = FILE_ROOT . $_rootdir;
		else $this->resDir = FILE_ROOT . $this->resDir;
			
		if (!empty($_cachedir)) $this->htmCacheDir = FILE_ROOT . $_cachedir;
		else $this->htmCacheDir = FILE_ROOT . $this->cacheHtmDir;

	}//end taglib function

	public function setView ($_tplname,$_force = 0) {
		global $_G;
		
		$tplFile = $this->resDir . 'htm' . DIRECTORY_SEPARATOR . $_G['modName'] . DIRECTORY_SEPARATOR . $this->htmName . DIRECTORY_SEPARATOR . $_tplname . '.' . $this->htmFileExt;
		$cacheFile = $this->htmCacheDir . $_tplname . '_cache.' . $this->htmCacheExt;
		
		if (!file_exists($tplFile)) {
			$tplFile = $this->resDir . 'htm' . DIRECTORY_SEPARATOR . $_tplname . '.' . $this->htmFileExt;
			$cacheFile = FILE_ROOT . $this->cacheHtmDir . $_tplname . '_cache.' . $this->htmCacheExt;
			if (!file_exists($tplFile)) die ("$tplFile not found!");
		}
	
		if (!is_dir(dirname($cacheFile))) @mkdir (dirname($objfile));
		if ((@filemtime($tplFile) > @filemtime($cacheFile)) || (!file_exists($cacheFile)) || (filesize($cacheFile) == 0) || ($_force == 1)) {
            if (!$fp = @fopen($cacheFile, 'w')) die ("$cacheFile have no access!");
            flock ($fp, 3);
            fwrite ($fp, $this->parseView ($tplFile));
            fclose ($fp);
		}//end if

		$_G['endTime'] = sprintf('%0.6f',sprintf('%.8f',array_sum(explode(' ', microtime()))) - $_G['startTime']);

		return $cacheFile;
	}//end setView function
	
	public function tplLanguage($_name = 'tpl') {
		global $_G;
		$tplName = (IN_SITE == true) ? $_G['wwwTplName'] : $_G['siteTplName'];
		return $this->resDir . 'lan' . DIRECTORY_SEPARATOR . $_G['langMeta'] . DIRECTORY_SEPARATOR . $tplName . DIRECTORY_SEPARATOR .  $_name . '.lang' . $_G['phpEx'];
	}

	public function parseView($_tplfile) {//解析摸版
		global $_T,$_L,$_G;

		if(!@$fp = fopen($_tplfile, 'r')) {
			die("Current file $_tplfile not found or have no access!");
		}
		elseif(!include $this->tplLanguage()) {
			die("<br />Current template pack do not have a necessary language file " . $this->taglibLanguage() . " or have syntax error!");
		}

		if (filesize($_tplfile)==0) die("Current file $_tplfile null" );

		$file_content = fread($fp, filesize($_tplfile));
		fclose($fp);

		$filename_dir = $this->resDir . $this->htmName . DIRECTORY_SEPARATOR;
		$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
		$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";

		$file_content = "<?php if(!defined('IN_LEKO')) {header(\"HTTP/1.0 403 Forbidden\");exit;} ?>\n$file_content";
		$file_content = preg_replace ("/[\n\r\t]*\(!template\s+$var_regexp!\)[\n\r\t]*/ies", "\$this->addquote('<?php include (\$_T->setView(\\1));?>')", $file_content);
		$file_content = preg_replace ("/[\s]*\(!template\s+(.+?)!\)[\s]*/is", "<?php \ninclude \$_T->setView('\\1'); ?>", $file_content);

		$file_content = preg_replace("/\<\!\-\-\(\!(.+?)\!\)\-\-\>/s", "(!\\1!)", $file_content);
		$file_content = preg_replace("/\(!lang\s+(.+?)!\)/ies", "\$this->languagevar('\\1')", $file_content);
		$file_content = preg_replace("/[\n\r\t]*\(!exec\s+(.+?)!\)[\n\r\t]*/ies", "\$this->stripvtags('<? \\1 ?>','')", $file_content);
		$file_content = preg_replace ("/[\n\r\t]*\(!elseif\s+(.+?)!\)[\n\r\t]*/ies", "\$this->stripvtags('<?php } elseif(\\1) { ?>', '')", $file_content);
		$file_content = preg_replace ("/[\n\r\t]*\(!else!\)[\n\r\t]*/is", "<?php } else { ?>", $file_content);
		for($i = 0; $i < 5; $i++)
		{
			$file_content = preg_replace ("/[\n\r\t]*\(!loop\s+([\$a-zA-Z0-9_-]+)\s+([\$a-zA-Z0-9_-]+)!\)[\n\r]*(.+?)[\n\r]*\(!\/loop!\)\s*/ies", "\$this->stripvtags('<?php if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\\3<? } } ?>')", $file_content);
			$file_content = preg_replace ("/\s*\(!loop\s+([\$a-zA-Z0-9_-]+)\s+([\$a-zA-Z0-9_-]+)\s+([\$a-zA-Z0-9_-]+)!\)\s*(.+?)\s*\(!\/loop!\)\s*/ies", "\$this->stripvtags('<?php if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\\4<? } } ?>')", $file_content);
			$file_content = preg_replace("/[\n\r\t]*\(!if\s+(.+?)!\)[\n\r]*(.+?)[\n\r]*\(!\/if!\)[\n\r\t]*/ies", "\$this->stripvtags('<? if(\\1) { ?>','\\2<? } ?>')", $file_content);
		}
		$file_content = preg_replace ("/\(!$var_regexp!\)/es", "\$this->addquote('<?php isset(\\1) && print(\\1);?>')", $file_content);

		return $file_content;
	}//end parseView function
	
	public function languagevar($_var) {
		if(isset($GLOBALS[$this->langHandle][$_var])) {
			return $GLOBALS[$this->langHandle][$_var];
		}
		else {
			return "!$_var!";
		}
	}

	public function addQuote($_var) {
		return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $_var));
	}
	
	public function stripvTags($_expr, $_statement) {
		$_expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $_expr));
		$_statement = str_replace("\\\"", "\"", $_statement);
		return $_expr.$_statement;
	}

	public function tpl($_tplfile,$_file) {
		$tplfile = $this->htmCacheDir . $file . '_' . $this->htmName . "_view." . $this->htmCacheExt;
		$returnfile = '<?php if(filemtime("' . $_tplfile . '")>filemtime("' . $tplfile . '")) { $_T->setView("' . $_file . '",1); }   ?>';
		$returnfile .= file_get_contents($_tplfile);
		return $returnfile;
	}
}

?>
